package org.ithang.application;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.ithang.application.account.bean.Account;
import org.ithang.application.account.service.AccountService;
import org.ithang.application.bcAddr.bean.BcAddr;
import org.ithang.application.bcAddr.service.BcAddrService;
import org.ithang.application.bcRecord.bean.BcRecord;
import org.ithang.application.bcRecord.service.BcRecordService;
import org.ithang.application.btAddr.bean.BtAddr;
import org.ithang.application.btAddr.service.BtAddrService;
import org.ithang.application.btRecord.bean.BtRecord;
import org.ithang.application.btRecord.service.BtRecordService;
import org.ithang.application.customer.bean.Customer;
import org.ithang.application.customer.service.CustomerService;
import org.ithang.application.invest.bean.Invest;
import org.ithang.application.invest.service.InvestService;
import org.ithang.application.notice.bean.Notice;
import org.ithang.application.notice.service.NoticeService;
import org.ithang.application.staticBonus.bean.StaticBonus;
import org.ithang.application.staticBonus.service.StaticBonusService;
import org.ithang.application.teamBonus.bean.TeamBonus;
import org.ithang.application.teamBonus.service.TeamBonusService;
import org.ithang.system.keyvalue.bean.Keyvalue;
import org.ithang.system.keyvalue.service.KeyvalueService;
import org.ithang.tools.eth.ETHUtil;
import org.ithang.tools.lang.DateUtils;
import org.ithang.tools.lang.MD5Util;
import org.ithang.tools.lang.StrUtils;
import org.ithang.tools.model.Action;
import org.ithang.tools.model.ActionResult;
import org.ithang.tools.model.Arith;
import org.ithang.tools.model.ErrorInfo;
import org.ithang.tools.model.Pager;
import org.ithang.tools.redis.JedisUtils;
import org.ithang.tools.redis.Keys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("app")
public class HomeAction extends Action<Object>{

	@Autowired
	private AccountService accountService;
	
	@Autowired
	private InvestService investService;
	
	@Autowired
	private StaticBonusService staticBonusService;
	
	@Autowired
	private TeamBonusService teamBonusService;
	
	@Autowired
	private KeyvalueService keyvalueService;
	
	@Autowired
	private BtRecordService btRecordService;
	
	@Autowired
	private BcRecordService bcRecordService;
	
	@Autowired
	private BtAddrService btAddrService;
	
	@Autowired
	private CustomerService customerService;
	
	@Autowired
	private BcAddrService bcAddrService;
	
	@Autowired
	private NoticeService noticeService;
	/**
	 * 首页数据
	 * @return
	 */
	@ResponseBody
	@RequestMapping("home")
	public ActionResult home(){
		Map<String,Object> result=new HashMap<>();
		Subject subject = SecurityUtils.getSubject();
    	if(subject.isAuthenticated()){
    		
    		//个人信息
    		Customer user=(Customer)subject.getPrincipal();
    		
    		user=customerService.get(user.getId());
    		
    		result.put("user", user);
    		
    		//账户信息&投资信息
    		Account account=accountService.getByCustomer(user.getId());
    		result.put("account", account);
    		
    		Pager<Notice> page=new Pager<Notice>();
    		Notice bean=new Notice();
    		bean.setState(1);
    		page.setBean(bean);
    		
    		List<Notice> notices=noticeService.page(page);
    		result.put("notices", notices);
    		result.put("verify_url", keyvalueService.get(Keys.VerifyURL).getValue());
    		
    		Keyvalue staticBonusRate=keyvalueService.get(Keys.StaticBonusRate);
    		if(null!=staticBonusRate){
    			result.put("static_rate", staticBonusRate.intValue());
    		}
    		
    		
    	}else{
    		return error(ErrorInfo.NoLoginError);
    	}
		return success(result);
	}
	
	
	@ResponseBody
	@RequestMapping("notices")
	public ActionResult notices(Pager<Notice> page){
		Subject subject = SecurityUtils.getSubject();
    	if(subject.isAuthenticated()){
    		Notice bean=new Notice();
    		bean.setState(1);
    		page.setBean(bean);
    		List<Notice> notices=noticeService.page(page);
    		page.setData(notices);
    		return success(page);
    	}else{
    		return error(ErrorInfo.NoLoginError);
    	}
	}
	
	
	/**
	 * 充值 ，返回充值地址
	 * @return
	 */
	@ResponseBody
	@RequestMapping("recharge")
	public ActionResult recharge(){
		Subject subject = SecurityUtils.getSubject();
    	if(subject.isAuthenticated()){
    		Customer user=(Customer)subject.getPrincipal();
    		BcAddr bc=bcAddrService.getByCustomer(user.getId());
    		
    		if(null==bc){
    			try{
    			    //创建钱包地址
    			    BcAddr bcAddr=new BcAddr();
    			    bcAddr.setCustomer_id(user.getId());
    			    bcAddr.setCurrency_id(1);
    			    bcAddrService.add(bcAddr);
    			    return success(bcAddr.getAddr());
    			}catch(Exception e){
    				e.printStackTrace();
    			}
    		}else{
    			return success(bc.getAddr());
    		}
    		
    	}
    	
    	return error(ErrorInfo.NoLoginError);
	}
	
	/**
     * 投资首页
     * @param invest
     * @return
     */
    @ResponseBody
   	@RequestMapping(value="invest/home")
   	public ActionResult self(){
    	Subject subject = SecurityUtils.getSubject();
    	if(subject.isAuthenticated()){
    		
    		//个人信息
    		Customer user=(Customer)subject.getPrincipal();
    		
    		Map<String,Object> data=new HashMap<>();
    		
    		Account account=accountService.getByCustomer(user.getId());
    		//投资信息
    		//总投资 //investService.getsInt("select sum(amount) from `invest` where user_id=?", user.getId());
    		double totalInvestAmount=account.getInvest_amount()==null?0:account.getInvest_amount();//investService.getsInt("select invest_amount from `account` where customer_id=?", user.getId());

    		if(null==account.getAddteam_bonus()){
    			account.setAddteam_bonus(0D);
    		}
    		
    		if(null==account.getTeam_bonus()){
    			account.setTeam_bonus(0D);
    		}
    		if(null==account.getStatic_bonus()){
    			account.setStatic_bonus(0D);
    		}
    		
    		//总收益
    		double totalRonus=Arith.round(Arith.add(Arith.add(account.getAddteam_bonus(),account.getStatic_bonus()),account.getTeam_bonus()),2);//investService.getsInt("select total_bonus from `account` where customer_id=?", user.getId());
    		
    		data.put("totalInvestAmount", totalInvestAmount);//总投资
    		data.put("totalRonus", totalRonus);//总收益
    		return success(data);
    	}else{
    		return error(ErrorInfo.NoLoginError);
    	}
   	}
    
    /**
     * 静态收益记录
     * @param page
     * @return
     */
    @ResponseBody
	@RequestMapping(value="staticbonus",method=RequestMethod.POST)
	public ActionResult staticBonus(Pager<StaticBonus> page){
    	
    	Subject subject = SecurityUtils.getSubject();
    	if(subject.isAuthenticated()){
    		Customer user=(Customer)subject.getPrincipal();
    		StaticBonus staticBonus=new StaticBonus();
    		staticBonus.setCustomer_id(user.getId());
    		page.setBean(staticBonus);
    		List<StaticBonus> data=staticBonusService.page(page);
    	    page.setData(data);
    		return success(page);
    	}else{
    		return error(ErrorInfo.NoLoginError);
    	}
    	
	}
    
    /**
     * 加速收益记录
     * @param page
     * @return
     */
    @ResponseBody
	@RequestMapping(value="teambonus",method=RequestMethod.POST)
	public ActionResult teamBonus(Pager<TeamBonus> page){
    	Subject subject = SecurityUtils.getSubject();
    	if(subject.isAuthenticated()){
    		Customer user=(Customer)subject.getPrincipal();
    		TeamBonus teamBonus=new TeamBonus();
    		teamBonus.setCustomer_id(user.getId());
    		page.setBean(teamBonus);
    		List<TeamBonus> data=teamBonusService.page(page);
    	    page.setData(data);
    		return success(page);
    	}else{
    		return error(ErrorInfo.NoLoginError);
    	}
	}
    
    /**
     * 动态收益记录
     * @param page
     * @return
     */
    @ResponseBody
	@RequestMapping(value="addteambonus",method=RequestMethod.POST)
	public ActionResult addTeamBonus(Pager<TeamBonus> page){
    	Subject subject = SecurityUtils.getSubject();
    	if(subject.isAuthenticated()){
    		Customer user=(Customer)subject.getPrincipal();
    		TeamBonus teamBonus=new TeamBonus();
    		teamBonus.setCustomer_id(user.getId());
    		teamBonus.setType(1);
    		page.setBean(teamBonus);
    		List<TeamBonus> data=teamBonusService.page(page);
    	    page.setData(data);
    		return success(page);
    	}else{
    		return error(ErrorInfo.NoLoginError);
    	}
	}
    
    /**
     * 投资记录
     * @param page
     * @return
     */
    @ResponseBody
	@RequestMapping(value="invests",method=RequestMethod.POST)
	public ActionResult invests(Pager<Invest> page){
    	Subject subject = SecurityUtils.getSubject();
    	if(subject.isAuthenticated()){
    		Customer user=(Customer)subject.getPrincipal();
    		Invest invest=new Invest();
    		invest.setCustomer_id(user.getId());
    		page.setBean(invest);
    		List<Invest> data=investService.page(page);
    	    page.setData(data);
    		return success(page);
    	}else{
    		return error(ErrorInfo.NoLoginError);
    	}
	}
    
    
    /**
     * 投资
     * @param amount 投资金额
     * @param paypass 投资密码
     * @return
     */
    @ResponseBody
	@RequestMapping(value="doinvest",method=RequestMethod.POST)
	public ActionResult doInvest(@RequestParam("amount")double amount,@RequestParam("paypass")String paypass){
    	Subject subject = SecurityUtils.getSubject();
    	if(subject.isAuthenticated()){
    		Customer user=(Customer)subject.getPrincipal();
    		
    		user=customerService.get(user.getId());
    		Account account=accountService.getByCustomer(user.getId());
    		
    		if(null!=account){
    			if(account.getAmount()<amount){
    				return error(ErrorInfo.BalanceNotEnoughError); 
    			}
    		}else{
    			account=new Account();
    			account.setCustomer_id(user.getId());
    			account.setCurrency_id(1);
    			account.setCreate_time(DateUtils.getSystime());
    			accountService.add(account);
    			return error(ErrorInfo.BalanceNotEnoughError); 
    		}
    		
    		if(null!=user.getPay_pwd()&&user.getPay_pwd().trim().length()>0){
    			String paypassMD5=MD5Util.md5(paypass);
    			if(paypassMD5.equals(user.getPay_pwd())){
    				
    				try{
    					
    					synchronized (HomeAction.class) {
    			    		String value=JedisUtils.get(String.valueOf(user.getId()));
    			    		if(null!=value){
    			    			return error(ErrorInfo.OperationTooManeyError);
    			    		}else{
    			    			JedisUtils.set(String.valueOf(user.getId()), "doinvest", 10);
    			    		}
    		    		}
    					
    					
    					
    				    investService.doInvest(amount, account);
    				    return success();
    				}catch(Exception e){
    					e.printStackTrace();
    					return error(ErrorInfo.InternalError);
    				}
    				
    			}else{
    				return error(ErrorInfo.PayPassError);
    			}
    		}else{
    			return error(ErrorInfo.NoPayPassError);
    		}
    		
    		
    	}else{
    		return error(ErrorInfo.NoLoginError);
    	}
	}
	
    
    /**
     * 提币
     * @param amount
     * @param btaddr
     * @return
     */
    @ResponseBody
	@RequestMapping(value="dowithdraw",method=RequestMethod.POST)
	public ActionResult doWithdraw(@RequestParam("amount")double amount,@RequestParam("addr")String addr){
    	Subject subject = SecurityUtils.getSubject();
    	if(subject.isAuthenticated()){
    		try{
    			
    			boolean valid=ETHUtil.checkAccount(addr);//判断地址是否有效
    			if(!valid){
    				return error(ErrorInfo.InvalidBtAddrError);
    			}
    			
    			
    			Customer user=(Customer)subject.getPrincipal();
    			
    			Account account=accountService.getByCustomer(user.getId());
    			
    			synchronized (HomeAction.class) {
    				String value=JedisUtils.get(String.valueOf(user.getId()));
            		if(null!=value){
            			return error(ErrorInfo.OperationTooManeyError);
            		}else{
            			JedisUtils.set(String.valueOf(user.getId()), "dowithdraw", 10);
            		}
				}
    			
    			
    			if(account.getAmount()<amount){
    				return error(ErrorInfo.BalanceNotEnoughError);
    			}
    			
    			btRecordService.doWithdraw(user, amount, addr);//提币申请
    		}catch(Exception e){
    			e.printStackTrace();
    			return error(ErrorInfo.InternalError);
    		}
    	}else{
    		return error(ErrorInfo.NoLoginError);
    	}
    	
    	
    	return success();
    }
    
    
    @ResponseBody
   	@RequestMapping(value="recharges",method=RequestMethod.POST)
   	public ActionResult recharges(Pager<BcRecord> page){
    	Subject subject = SecurityUtils.getSubject();
    	if(subject.isAuthenticated()){
    		Customer user=(Customer)subject.getPrincipal();
    		BcRecord bt=new BcRecord();
    		bt.setCustomer_id(user.getId());
    		page.setBean(bt);
    		List<BcRecord> data=bcRecordService.page(page);
    		return success(data);
    	}else{
    		return error(ErrorInfo.NoLoginError);
    	}
    }
    
    /**
     * 提币记录
     * @param page
     * @return
     */
    @ResponseBody
	@RequestMapping(value="withdraws",method=RequestMethod.POST)
	public ActionResult withdraws(Pager<BtRecord> page){
    	Subject subject = SecurityUtils.getSubject();
    	if(subject.isAuthenticated()){
    		Customer user=(Customer)subject.getPrincipal();
    		BtRecord bt=new BtRecord();
    		bt.setCustomer_id(user.getId());
    		page.setBean(bt);
    		List<BtRecord> data=btRecordService.page(page);
    		return success(data);
    	}else{
    		return error(ErrorInfo.NoLoginError);
    	}
    }
    
    @ResponseBody
   	@RequestMapping(value="btaddrs",method=RequestMethod.POST)
   	public ActionResult btAddrs(Pager<BtAddr> page){
       	Subject subject = SecurityUtils.getSubject();
       	if(subject.isAuthenticated()){
       		Customer user=(Customer)subject.getPrincipal();
       		BtAddr bt=new BtAddr();
       		bt.setCustomer_id(user.getId());
       		page.setBean(bt);
       		List<BtAddr> data=btAddrService.page(page);
       		return success(data);
       	}else{
       		return error(ErrorInfo.NoLoginError);
       	}
   }
    
    @ResponseBody
   	@RequestMapping(value="ratevalue",method=RequestMethod.POST)
   	public ActionResult ratevalue(String amount){
    	if(!StrUtils.isNumber(amount)){
    		return error(ErrorInfo.NumberError);
    	}
    	Keyvalue kv=keyvalueService.get(Keys.Charge);
    	Double r=Arith.mul((Arith.div(kv.doubleValue(),100D,2)),Double.valueOf(amount));
    	return success(r);
    }
    
    @ResponseBody
   	@RequestMapping(value="getrate",method=RequestMethod.GET)
   	public ActionResult getrate(String amount){
    	Keyvalue kv=keyvalueService.get(Keys.Charge);
    	return success(kv.doubleValue());
    }
    
	
}
